package com.example.abc.web.account;

import com.example.abc.common.Constants;
import com.example.abc.common.DataTableRequest;
import com.example.abc.common.DataTableResponse;
import com.example.abc.common.RestResponse;
import com.example.abc.dto.MyUserDetails;
import com.example.abc.dto.Profile;
import com.example.abc.dto.account.AccountAuthSaveDto;
import com.example.abc.dto.account.AuthorityTreeDto;
import com.example.abc.entity.Account;
import com.example.abc.exception.ClientException;
import com.example.abc.exception.ServerException;
import com.example.abc.service.AccountService;
import com.example.abc.service.AuthorityService;
import com.example.abc.util.ImageUtil;
import com.example.abc.util.JsonUtil;
import com.example.abc.web.IndexController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestClientException;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.security.Principal;
import java.util.List;
import java.util.Random;

/**
 * Created by Peter on 2018/4/27.
 */
@Controller
public class AccountController {
    public static final Logger logger = LoggerFactory.getLogger(IndexController.class);

    @Autowired
    private AccountService accountService;

    @RequestMapping(value = "/accounts", method = {RequestMethod.GET})
    public String accounts(Model model) {
        return "account/accounts";
    }

    @RequestMapping(value = "/accounts", method = {RequestMethod.POST})
    @ResponseBody
    public DataTableResponse accountData(HttpServletRequest request, Model model) {
        DataTableRequest dataTableRequest = new DataTableRequest(request);
        logger.info(Constants.prefix_in + JsonUtil.toJson(dataTableRequest));
        DataTableResponse response = accountService.seach(dataTableRequest);
        logger.info(Constants.prefix_out + JsonUtil.toJson(response));
        return response;
    }

    @RequestMapping(value = "/accounts/edit/{id}", method = {RequestMethod.GET})
    public String accountData(@PathVariable Long id, Model model) {
        logger.info(Constants.prefix_in + "id=" + id);
        Account account = accountService.findById(id);
        model.addAttribute("account", account);
        return "account/account-edit";
    }

    @RequestMapping(value = "/accounts/auth/{id}", method = {RequestMethod.GET})
    public String accountAuth(@PathVariable Long id, Model model) {
        logger.info(Constants.prefix_in + "id=" + id);
        // 用户信息
        Account account = accountService.findById(id);
        model.addAttribute("account", account);

        // 用户权限信息
        List<AuthorityTreeDto> list = accountService.getUserAuthTree(id);
        model.addAttribute("data", JsonUtil.toJson(list));

        return "account/account-authorities";
    }

    @RequestMapping(value = "/accounts/auth/save/{uid}", method = {RequestMethod.POST})
    @ResponseBody
    public RestResponse saveAccountAuth(@PathVariable String uid, @RequestParam(value = "authorityIds[]", defaultValue = "") List<Long> authorityIds, Model model) {
        try {
            logger.info(Constants.prefix_in + "uid:" + uid + ", authorityIds:" + JsonUtil.toJson(authorityIds));
            if (authorityIds == null || authorityIds.size() == 0) {
                throw new RestClientException("");
            }
            // 保存用户权限
            accountService.saveAccountAuth(uid, authorityIds);
            RestResponse restResponse = RestResponse.getSuccessResponse();
            return restResponse;
        } catch (ClientException e) {
            logger.error(e.getMessage(), e);
            return RestResponse.getClientErrorResponse(e.getMessage());
        } catch (ServerException e) {
            logger.error(e.getMessage(), e);
            return RestResponse.getServerErrorResponse(e.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return RestResponse.getServerErrorResponse(e.getMessage());
        }

    }

    @RequestMapping(value = "/profile", method = {RequestMethod.GET})
    public String profile(Model model, Principal principal) {
        Account account = accountService.findByUsername(principal.getName());
        model.addAttribute("account", account);
        return "account/profile";
    }

    @RequestMapping(value = "/profile", method = {RequestMethod.POST})
    public String profileSave(@ModelAttribute Profile profile, Model model) {
        logger.info(Constants.prefix_in + JsonUtil.toJson(profile));
        Account account = accountService.updateProfile(profile);
        model.addAttribute("account", account);
        return "account/profile";
    }

    @RequestMapping(value = "/profile/avatar/save", method = {RequestMethod.POST})
    @ResponseBody
    public RestResponse saveAvatar(@RequestParam("avatar") String base64Avatar) {
        try {
            logger.info(Constants.prefix_in);
            logger.info(base64Avatar);
            MyUserDetails account = (MyUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            String avatar_url = accountService.saveAvatar(account, base64Avatar);

            RestResponse restResponse = RestResponse.getSuccessResponse(avatar_url);
            return restResponse;
        } catch (ClientException e) {
            logger.error(e.getMessage(), e);
            return RestResponse.getClientErrorResponse(e.getMessage());
        } catch (ServerException e) {
            logger.error(e.getMessage(), e);
            return RestResponse.getServerErrorResponse(e.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return RestResponse.getServerErrorResponse(e.getMessage());
        }
    }


    @RequestMapping(value = "/fileUploadDemo", method = {RequestMethod.POST})
    public String FileUploadDemo(@RequestParam("file") MultipartFile file) {
        logger.info(Constants.prefix_in);
        logger.info(file.getName());
        logger.info(file.getOriginalFilename());
        logger.info(file.getContentType());
        logger.info("" + file.getSize());

        return "account/profile";
    }

}
